<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="btnEdit">用户编辑</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" ref="multipleTable" :data="userList" style="width:100%" @selection-change="handleSelectionChange" @select="select" @select-all="selectAll" border>
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" prop="Id" />
          <el-table-column label="用户名称" align="center" prop="UserName" />
          <el-table-column label="用户昵称" align="center" prop="RealName" />
          <el-table-column label="角色名称" align="center">
            <template slot-scope="scope">
              <el-tag v-for="(item, index) in scope.row.Roles" :key="index" type="primary" size="small">{{ item.RoleName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" align="center" prop="Email" />
          <el-table-column label="手机号码" align="center" prop="Phone" width="120" />
          <el-table-column label="状态" align="center" prop="Status">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.Status" :active-value="1" :inactive-value="0" @change="handleStatusChange($event, scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="CreateOn" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.CreateOn) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" prop="action" width="300" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="btnassRole(scope.row)">分配角色</el-button>
              <el-button size="mini" type="warning" icon="el-icon-edit" @click="btnChange(scope.row)">重置</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="btnDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 用户添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="RealName">
              <el-input v-model="form.UserName" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="Phone">
              <el-input v-model="form.Phone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="Email">
              <el-input v-model="form.Email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.Id == undefined" label="用户昵称" prop="userName">
              <el-input v-model="form.RealName" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.Id == undefined" label="用户密码" prop="PassWord">
              <el-input v-model="form.PassWord" placeholder="请输入用户密码" type="password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio v-model="form.Status" :label="1">可用</el-radio>
              <el-radio v-model="form.Status" :label="0">不可用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
      
	   <!-- 分配角色对话框 -->
    <el-dialog :visible.sync="roleopen" :title="roleformtitle" @close="cancel">
      <el-form class="text-c">
        <el-form-item>
          <el-transfer
            style="text-align: left; display: inline-block;"
            filterable
            v-model="selectedRoles"
            :data="allRoles"
            :titles="['可选角色', '已选角色']"
          ></el-transfer>
        </el-form-item>
      </el-form>
      <el-row class="text-c mt-10">
        <el-button icon="el-icon-close" @click="roleopen=false">取消</el-button>
        <el-button type="primary" icon="el-icon-check" @click="submitAssRoleForm">提交</el-button>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  assignUserRoles,
  updateUser,
  resetUserPwd,
  changeUserStatus
} from "@/api/system/user";
import {
  getAllRoleList
} from "@/api/system/role";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css"; //

export default {
  name: "User",
  components: {
    Treeselect
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 表格选中的行
      multipleSelection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // role弹出层标题
      roleformtitle: "",
      // 是否显示弹出层
      open: false,
      roleopen: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],

	  selectedRoles: [], // 所选的角色ID
      allRoles: [],      // 所有角色对象 id，name

      // 表单参数
      form: {
        Id: undefined,
        UserName: undefined,
        RealName: undefined,
        PassWord: undefined,
        Phone: undefined,
        Email: undefined,
        Gender: undefined,
        Status: "0",
        Roles: []
      },
      // 用户角色弹出
      userroleform: {

      },

      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {
        UserName: [{
          required: true,
          message: "用户名称不能为空",
          trigger: "blur"
        }],
        PassWord: [{
          required: true,
          message: "用户密码不能为空",
          trigger: "blur"
        }]
      }
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList () {
      this.loading = true;
      listUser({
        pageIndex: 1,
        pageSize: 50
      }).then(response => {
        const res = response.data;
        this.userList = res.data;
        this.total = res.dataCount;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 用户状态修改
    handleStatusChange (val, row) {
	  var userid =row.Id;
      const text = val === 0 ? "停用" : "启用";
      this.$confirm('确认要"' + text + '""' + row.UserName + '"用户吗?',"警告", { confirmButtonText: "确定",cancelButtonText: "取消", type: "warning" })
        .then(function () {
          console.log(userid + "---" + val)
          return changeUserStatus(userid, val);
        })
        .then(res => {
          if (res.success) {
            this.msgSuccess(text + "成功");
          } else {
            this.msgError(text + "失败");
            row.Status = val === 0 ? 1 : 0;
          }
        })
        .catch(function () {
          row.Status = val === 0 ? 1 : 0;
        });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.roleopen = false;
	  this.allRoles=[],
	  this.selectedRoles=[],
      this.reset();
      this.userroleform = {};
      this.resetForm("userroleform"); //全局重置表单
    },
    // 表单重置
    reset () {
      this.form = {
        Id: undefined,
        UserName: undefined,
        RealName: undefined,
        PassWord: undefined,
        Phone: undefined,
        Email: undefined,
        Gender: undefined,
        Status: "0",
        Roles: []
      };
      this.resetForm("form"); //全局重置表单
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.page = 1;
      this.getList();
    },
    // 表格多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.Id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    select (selection) {
      // 选择项大于1时
      if (selection.length > 1) {
        let del_row = selection.shift();
        // console.log('把数组的第一个元素从其中删除后', selection);
        this.$refs.multipleTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
      }
    },

    selectAll (selection) {
      // 选择项大于1时
      if (selection.length > 1) {
        selection.length = 1;
      }
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    btnEdit () {
      console.log(this.$refs.multipleTable.selection)
      if (this.$refs.multipleTable.selection.length < 1) {
        this.msgError("当前未选中任何行，请勾选对应的用户！！！");
        return;
      }
      const row = this.$refs.multipleTable.selection[0];
      this.reset();
      const userId = row.Id;
      this.form = JSON.parse(JSON.stringify(row)); //利用JSON进行深拷贝
      this.open = true;
      this.title = "修改用户";

    },
    /** 分配角色按钮 */
    btnassRole (row) {

      this.userroleform = JSON.parse(JSON.stringify(row));//利用JSON进行深拷贝
      this.roleformtitle = "分配"+`${ this.userroleform.UserName}`+"角色";
      getAllRoleList().then(res => {
		 for (let i = 0; i <res.data.data.length; i++) {
          this.allRoles.push({
            key: res.data.data[i].Id,
            label: res.data.data[i].RoleName,
          })}

		this.selectedRoles = this.userroleform.Roles.map(item =>item.Id);  //筛选id
		this.roleopen = true;
      });
    },
    /** 重置密码按钮操作 */
    btnChange (row) {
      this.$confirm('重置"' + row.UserName + '"密码：123456，是否继续?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(() => {
          resetUserPwd(row.Id, "123456").then(response => {
            this.msgSuccess("修改成功!");
          });
        })
        .catch(() => { });
    },
    /** 删除按钮操作 */
    btnDelete (row) {
      const userIds = parseInt(row.Id);
      this.$confirm(
        '是否确认删除用户编号为"' + userIds + '"的数据项?',
        "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
      )
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },



    /** 分配角色界面提交 */
    submitAssRoleForm () {
      assignUserRoles(this.userroleform.Id, this.selectedRoles).then(res => {
        if (res.success) {
		  this.getList();
          this.msgSuccess("分配成功");
          this.roleopen = false;
        } else {
          this.msgError("分配失败");
        }
      }).catch(() => {
        this.msgError("分配失败");
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.Id != undefined) {
            updateUser(this.form).then(response => {
              if (response.success) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError("修改失败");
              }
            });
          } else {
            addUser(this.form).then(response => {
              if (response.success) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError("新增失败");
              }

            });
          }
        }
      });
    },

  }
};
</script>

<style scoped lang="scss">
.user-info-head {
  position: relative;
  display: inline-block;
  height: 120px;
}


.demo-drawer__content{
	padding: 15px;
}


</style>